<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/layui.css">
    <link rel="stylesheet" href="../css/modules/layer/default/layer.css">
    <title>文件库</title>
</head>
<body>
    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        <div id="uploadImg" class="layui-upload">
        <button type="button" class="layui-btn" id="upload">
            <i class="layui-icon">&#xe67c;</i>上传文件<span style="color: red;font-size: 20px;">*</span>
        </button>
        <div class="layui-upload-list">
            <table class="layui-table" style="text-align: center;">
                <thead>
                <tr>
                    <th style="text-align: center;">文件预览</th>
                    <th style="text-align: center;">文件名</th>
                    <th style="text-align: center;">大小</th>
                    <th style="text-align: center;">状态</th>
                    <th style="text-align: center;">操作</th>
                </tr>
                </thead>
                <tbody id="imgList"></tbody>
            </table>
        </div>
        <button type="button" class="layui-btn" id="startUpload">开始上传</button>
            <div style="color: #c2c2c2;margin:10px 0;">
            </div>
    </div>
    <input type="text" name="face_img" id="imgInput" style="display: none;" lay-verify="required">
</blockquote>

    <script src="../js/layui.js"></script>
    <script>
        // 是否是图片格式
        function isImage(fileName){
            var Ttype="";
            //后缀获取
            var suffix = '';
            // 获取类型结果
            var result = '';
            var flieArr = fileName.split('.');
            suffix = flieArr[flieArr.length - 1];
            if(suffix!=""){
                suffix = suffix.toLocaleLowerCase();
                // 图片格式
                const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
                // 进行图片匹配
                result = imglist.find(item => item === suffix);
                if (result) return true;
                return false;

            }
        }
        // 随机颜色
        function randomColor() {
            var col = "#";
            for (var i = 0; i < 6; i++) col+=parseInt(Math.random() * 16).toString(16);
            return col;
        }
        // 防止xss
        function checkData(v) {
            var entry = { "'": "&apos;", '"': '&quot;', '<': '&lt;', '>': '&gt;' };
            v = v.replace(/(['")-><&\\\/\.])/g, function ($0) { return entry[$0] || $0; });
            return v;
            }

        layui.use(['table', 'form', 'element', 'upload','layer'], function () {
        var table = layui.table;
        var form = layui.form;
        var element = layui.element;
        var $ = layui.jquery;
        var upload = layui.upload;
        var layer = layui.layer;
        var findParent = parent.layui.jquery;
        
        //多文件列表示例
        var demoListView = $('#imgList');
        var totalArray = new Array();
        var uploadInst = upload.render({
            elem: '#upload' //绑定元素
            , url: '/uploadFile' //上传接口
            , accept: 'file'  // 允许上传的文件类型
            // , acceptMime: 'image/jpg,image/png'   // (只支持jpg和png格式，多个用逗号隔开),
            , size: 0                // 最大允许上传的文件大小  单位 KB
            , auto: false //选择文件后不自动上传
            , bindAction: '#startUpload' //指向一个按钮触发上传
            , multiple: true   // 开启多文件上传
            , number: 10    //  同时上传文件的最大个数
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                var arr = Object.keys(files);

                //读取本地文件
                obj.preview(function (index, file, result) {
                    console.log("index",index);
                    console.log("file",file);
                    // console.log("result",result);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , isImage(file.name)?'<td><img src="' + result + '" alt="' + file.name + '" class="layui-upload-img" style="height: 66px;width:100px;"></td>':'<td><i class="layui-icon layui-icon-file-b" style="font-size: 30px; color: '+randomColor()+';"></i></td>' 
                        , '<td>' + checkData(file.name) + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                });

            }
            , done: function (res, index, upload) {
                console.log("res", res);
                if (res.code == 0) { //上传成功
                    // 上传成功后将图片路径拼接到input中，多个路径用","分割
                    var inputVal = document.getElementById("imgInput").value;
                    var valData = "";
                    if (inputVal) {
                        valData = inputVal + "," + res.data[0].fp_relative;
                    } else {
                        valData = res.data[0].fp_relative;
                    }
                    document.getElementById("imgInput").value = valData;
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
                    // tds.eq(4).html(''); //清空操作
                    // console.log(res.data)
                    tds.eq(4).html(res.data[0].fp_relative); //清空操作

                    return delete this.files[index]; //删除文件队列已经上传成功的文件

                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(3).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传


            }
            ,allDone: function(obj){ //当文件全部被提交后，才触发
                var cur =  findParent(".layui-laypage-skip").find("input").val(); 
                var limit = findParent(".layui-laypage-limits").find("option:selected").val();
                console.log(obj.total); //得到总文件数
                console.log(obj.successful); //请求成功的文件数
                console.log(obj.aborted); //请求失败的文件数
                parent.layui.table.reload('filleTableId',{
                            url:"/fileLib",
                            // type:"post",
                            where: {
                                page:cur,
                                limit:limit
                            }
                            ,page: {
                                curr: cur //重新从第 1 页开始
                            }
                        });
            }
        });
    });
    </script>
</body>
</html>